import Vue from 'vue'
import Vuex from 'vuex'
import methodY from '@/util/methodY.js';
import webSocketUtil from '@/util/webSocketUtil.js';
Vue.use(Vuex)
 
const store = new Vuex.Store({
  state: {
	'activeTab':"",//底部导航栏
	webSocketConnected:false,//默认webSocket连接失败flase
	msg:{
		msgData:{},
		count:0
	},
    count: 0
  },
  mutations: {
	updateWebSocketConnected(state,webSocketConnected){
		console.log("websocket状态连接已被修改");
		state.webSocketConnected=webSocketConnected;
	},//修改WebSocket状态
	getWebSocketMsg(state,msgData){
		console.log("获取的websocket数据为：",msgData);
		//数据
		let sign=msgData.msg;
		let data=msgData.data;
		let code=msgData.code;
		
		console.log(sign,data,code);
		if("MSG"===sign){
			const userInfo = methodY.util.getUserInfo() || {};
			const userId = userInfo.userId;
			let chatListStr = uni.getStorageSync('chatList'+userId);
			let chatList= chatListStr ? JSON.parse(chatListStr) : [];
			let anonymousKey= uni.getStorageSync('anonymousKey'+userId) || 0;
			console.log(userId,anonymousKey);
			console.log("处理msg消息",Array.isArray(data),data,typeof data=== 'string')
			// 1. 参数标准化（确保是数组） 
			const messages = JSON.parse(data);
						
			messages.forEach(msg => {
				//修改为
				let sign="SEND_MSG";
				if(msg.sign==="true"){
				    sign= "ANONYMOUS_MSG"
				}else{
				   sign= "SEND_MSG"
				}
			   const chatIndex = webSocketUtil.util.findChatIndex(chatList,msg,sign);
			   
			   if (chatIndex >= 0) {
			    chatList= webSocketUtil.util.updateExistingChat(chatList,chatIndex,methodY.addr, msg,sign);
				console.log("新消息更新聊天列表为:",chatList);	
			   } else {
				 console.log("msg新消息需要创建",msg)
				 let obj=webSocketUtil.util.createNewChat(chatList,anonymousKey,methodY.addr,msg,sign);
			    chatList= obj.chatList;
				anonymousKey=obj.anonymousKey;
			   }
						  
			 });
			uni.setStorageSync('chatList'+userId, JSON.stringify(chatList));
			webSocketUtil.util.saveAnonymousCount(anonymousKey,userId);
			console.log("msg导致的新的聊天列表为:",chatList);
		}
		state.msg.msgData=msgData;
		state.msg.count=state.msg.count+1;
	},
	setActiveTab(state,url){
		state.activeTab=url;
	},
    increment(state) {
      state.count++
    }
  },
  actions: {
    increment(context) {
      context.commit('increment')
    }
  },
  getters: {
	msg:state => state.msg,
    count: state => state.count,
	webSocketConnected:state => state.webSocketConnected,
	activeTab:state=>state.activeTab,
  }
})
 
export default store